package com.mine.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.mine.result.CodeMsg;
import com.mine.result.Result;



public class GlobalExceptionResolver implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {

		exception.printStackTrace();
		
		ModelAndView modelAndView = new ModelAndView();
		
		 /*  使用response返回    */
		 response.setStatus(HttpStatus.OK.value()); //设置状态码  
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType  
        response.setCharacterEncoding("UTF-8"); //避免乱码  
        //输出服务器异常给客户端
        String jsonString = JSON.toJSONString(Result.error(CodeMsg.SERVER_ERROR));
        response.setHeader("Cache-Control", "no-cache, must-revalidate");  
        try {  
            response.getWriter().write(jsonString);  
        } catch (IOException e) {  
           //log.error("与客户端通讯异常:"+ e.getMessage(), e);
        	e.printStackTrace();
        }  
        
        return modelAndView;
	}

}
